<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Db;
use kuange\qqconnect\QC;

class Login extends Controller
{
	//登陆时判断是否已经登陆
	public function _initialize()
    {
        if(Session::has('Username')&&Session::has('UserId'))
        {
            $this->success('您已登录!','../');
        }
    }
	public function index()
	{
    	return $this->fetch('login');
	}

	/*用户登陆方法*/
	public function userlogin()
	{
		$user = model('User');
		$param = request()->param();
		$param['ip'] = request()->ip();
		$data = $user->userlogin($param);
		if($data){
			$msg = Db::name('user')->where('email',$param['email'])->select();
	        Session::set('Username',$msg[0]['username']);
	        Session::set('UserId',$msg[0]['id']);
	        return json(['message'=>'账号登陆成功']);
		}
		return json(['message'=>$user->getError()]);
	}

//QQ登陆绑定
	public function userqqlogin()
	{
		$param = request()->post();
		$param['ip'] = request()->ip();
		$param['password'] = pwd_md5($param['password']);
		$map['email'] = $param['email'];
		$map['password'] = $param['password'];
		$datas = Db::name('user')->where($map)->select();
		if(!$datas){
			return json(['message'=>'不存在的账户或错误的密码!']);
		}
		$result = Db::name('user')->where('id',$datas[0]['id'])->update(['openid'=>$param['openid']]);
		if($result){
	        Session::set('Username',$result[0]['username']);
	        Session::set('UserId',$result[0]['id']);
	        return json(['message'=>'绑定成功!']);
		}else{
	        return json(['message'=>'绑定失败!']);
		}
	}

	public function qqlg()
	{
		$qc = new QC();
        return redirect($qc->qq_login());
	}

	public function qqlogin()
	{
		$qc = new QC();
        $access_token =  $qc->qq_callback();    // access_token
        $openid = $qc->get_openid();     // openid
        $data['access_token'] = $access_token;
        $data['openid'] = $openid;
        // 待处理用户逻辑
        $result = Db::name('user')->where('openid',$openid)->select();
        if($result){
        	Session::set('Username',$result[0]['username']);
	        Session::set('UserId',$result[0]['id']);
	        $this->success('登陆成功!','../');
        }else{
        	$this->assign('data',$data);
        	return $this->fetch('login/qqindex');
        }
	}
	//绑定登陆
}
